package com.logicbus.service;

import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.Script;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.PropertiesConstants;
import com.logicbus.backend.AbstractServant;
import com.logicbus.backend.Context;
import com.logicbus.backend.message.JsonMessage;
import com.logicbus.backend.message.YamlMessage;
import com.logicbus.models.servant.ServiceDescription;
import org.apache.commons.lang3.StringUtils;

/**
 * 输出Swagger文档
 *
 * @since 1.6.13.7 [20200812 duanyy] <br>
 */
public class ServiceSwagger extends AbstractServant {
    protected static final String DEFAULT_SWAGGER = "java:///com/logicbus/service/servant.swagger.xml#" + ServiceSwagger.class.getName();
    protected Script script = null;

    @Override
    protected void onDestroy() {
    }

    @Override
    protected void onCreate(ServiceDescription sd) {
        script = Script.Library.create(
                PropertiesConstants.getString(sd.getProperties(),"swagger.main",DEFAULT_SWAGGER),
                sd.getProperties());
    }

    @Override
    protected int onJson(Context ctx)  {
        if (script != null){
            JsonMessage msg = (JsonMessage) ctx.asMessage(JsonMessage.class);

            LogicletContext logicletContext = new Context.ServantLogicletContext(ctx);
            try {
                XsObject doc = new JsonObject("root",msg.getRoot());
                script.execute(doc,doc, logicletContext, null);
            }finally{
                String keyword = logicletContext.GetValue("$keyword", "");
                if (StringUtils.isNotEmpty(keyword)){
                    ctx.setKeyword(keyword);
                }

                String outputPath = logicletContext.GetValue("$outpath", "");
                if (StringUtils.isNotEmpty(outputPath)){
                    msg.setOutputPath(outputPath);
                }
            }
        }else{
            ctx.asMessage(JsonMessage.class);
        }
        return 0;
    }

    @Override
    protected int onYaml(Context ctx)  {
        if (script != null){
            YamlMessage msg = (YamlMessage) ctx.asMessage(YamlMessage.class);

            LogicletContext logicletContext = new Context.ServantLogicletContext(ctx);
            try {
                XsObject doc = new JsonObject("root",msg.getRoot());
                script.execute(doc,doc, logicletContext, null);
            }finally{
                String keyword = logicletContext.GetValue("$keyword", "");
                if (StringUtils.isNotEmpty(keyword)){
                    ctx.setKeyword(keyword);
                }
                String outputPath = logicletContext.GetValue("$outpath", "");
                if (StringUtils.isNotEmpty(outputPath)){
                    msg.setOutputPath(outputPath);
                }
            }
        }else{
            ctx.asMessage(YamlMessage.class);
        }
        return 0;
    }
}